document.addEventListener('DOMContentLoaded', function() {
    const resultDiv = document.getElementById('result');
    const historyDiv = document.getElementById('history');
    const exportBtn = document.getElementById('export-btn');
    const clearBtn = document.getElementById('clear-btn');

    // 初始化历史记录
    let history = JSON.parse(localStorage.getItem('carbonHistory')) || [];

    // 显示历史记录
    function displayHistory() {
        historyList.innerHTML = '';
        history.forEach(function(record, index) {
            const li = document.createElement('li');
            li.textContent = `时间: ${record.time}, 活动类型:${record.activity}, 碳排放量: ${record.amount}`;
            historyList.appendChild(li);
        });
    }

    // 保存历史记录到本地存储
    function saveHistory() {
        localStorage.setItem('carbonHistory', JSON.stringify(history));
    }

    // 清除历史记录
    function clearHistory() {
        history = [];
        localStorage.removeItem('carbonHistory');
        displayHistory();
    }

    // 导出历史记录为CSV
    function exportToJsonFile() {
        if (history.length === 0) {
            alert('没有历史记录可以导出。');
            return;
        }
        let data = '时间,活动类型,碳排放量\n';
        history.forEach(function(record) {
            data += `${record.time},${record.activity},${record.amount}\n`;
        });
        const blob = new Blob([data], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        if (link.download !== undefined) { // feature detection
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', 'carbon-history.csv');
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }

    // 表单提交事件处理
    carbonForm.addEventListener('submit', function(event) {
        event.preventDefault();

        const time = new Date().toLocaleString();
        const distance = parseFloat(document.getElementById('distance').value);
        const publicTransport = parseFloat(document.getElementById('publicTransport').value);
        const meatConsumption = parseFloat(document.getElementById('meatConsumption').value);
    
        // 假设的系数
        const distanceFactor = 0.2; // 每公里产生的碳排放量
        const publicTransportFactor = -0.1; // 每次使用公共交通减少的碳排放量
        const meatFactor = 2.3; // 每公斤肉类产生的碳排放量
    
        // 计算碳排放
        const carbonEmission = (distance * distanceFactor) 
                            + (publicTransport * publicTransportFactor) 
                            + (meatConsumption * meatFactor);
        
        const result = { time, carbonEmission };

        // 显示结果
        const resultDiv = document.getElementById('result');
        resultDiv.innerHTML = `<strong>您的碳排放量约为：${result.carbonEmission.toFixed(2)} kg CO2</strong>`;
    
        history.unshift(result); // 逆序保存
        displayHistory();
        saveHistory();
    });

    // 绑定清除历史记录按钮
    clearBtn.addEventListener('click', clearHistory);

    // 绑定导出按钮
    exportBtn.addEventListener('click', exportToJsonFile);

    // 页面加载时显示历史记录
    displayHistory();
});
